package com.share.example.stock.web;

import com.share.common.common.Result;
import com.share.common.utils.DateUtil;
import com.share.common.utils.ThreadUtil;
import com.share.example.stock.enums.IndicatorEnum;
import com.share.example.stock.model.db.SectorSpot;
import com.share.example.stock.service.ISectorDetailService;
import com.share.example.stock.service.ISectorSpotService;
import com.share.example.stock.service.ITradeDateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author author
 * @since 2023-06-03
 */
@Slf4j
@RestController
@RequestMapping("/sectorspot")
public class SectorSpotController {
    @Autowired
    private ITradeDateService iTradeDateService;
    @Autowired
    private ISectorSpotService iSectorSpotService;
    @Autowired
    private ISectorDetailService iSectorDetailService;

    /**
     * 下载数据
     */
    @RequestMapping("/down")
    public Result list(String indicator) {
        //非工作日直接跳过
        if (!iTradeDateService.isTradeDay(new Date())) {
            return Result.failure("非交易日直接退出");
        }

        List<String> list = new LinkedList<>();
        IndicatorEnum values = IndicatorEnum.toEnum(indicator);
        if (values != null) {
            list.add(indicator);
        } else {
            Arrays.stream(IndicatorEnum.values()).forEach(e -> list.add(e.getCode()));
        }

        String res = null;
        for (String indicatorName : list) {
            try {
                List<SectorSpot> obj = iSectorSpotService.downSector(indicatorName);
            } catch (Exception e) {
                log.error("下载失败indicator={}", indicatorName, e);
                res = e.getMessage();
            }
        }

        return Result.success(res);
    }

    @RequestMapping("/downDetail")
    public Result downDetail() {
        Date date = new Date();
        String strTradeDate = DateUtil.getDate(date);//拉取数据的交易日时间
        //非工作日直接跳过
        if (!iTradeDateService.isTradeDay(date)) {
            return Result.failure("非交易日直接退出");
        }

        List<SectorSpot> list = iSectorSpotService.listLables();
        iSectorDetailService.resetErrorCount(0);
        ThreadUtil.execute(() -> iSectorDetailService.downSectorDetail(list, strTradeDate));
        return Result.success("任务已提交size=" + list.size());
    }
}
